package com.juyu.miliao.api.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author jh
 * 2018/10/19
 */
public class FileUtil {

    /**
     * 功能：Java读取txt文件的内容 步骤：
     * * 1：先获得文件句柄
     * * 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * * 3：读取到输入流后，需要读取生成字节流
     * * 4：一行一行的输出。readline()。 备注：需要考虑的是异常情况
     *
     * @param filePath 文件地址
     * @param encoding "GBK" "UTF-8"
     * @return String
     */
    public static String readTxtFile(String filePath, String encoding) {
        try {

            File file = new File(filePath);
            // 判断文件是否存在
            if (file.isFile() && file.exists()) {
                // 考虑到编码格式
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                StringBuilder sb = new StringBuilder();
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    sb.append(lineTxt);
                }
                read.close();
                return sb.toString();

            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return null;
    }

    public static void writeTxtFile(String filepath) {
        File file = new File(filepath);
        BufferedWriter writer = null;
        try {
            if (file.isFile() && !file.exists()) {
                System.out.println("找不到指定的文件");
                // 不存在则创建
                file.createNewFile();
            } else {
                //writer = new BufferedWriter(new FileWriter(file,true)); //这里加入true 可以不覆盖原有TXT文件内容 续写
                writer = new BufferedWriter(new FileWriter(file));
                writer.write("hello");
                writer.write("\n");
                writer.write("hello");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void writeToTxtFile(String content,String filepath){
        File file = new File(filepath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
           // BufferedWriter bw = new BufferedWriter(fw);
            fw.write(content+"\r\n");
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
